package com.example.definedview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import com.example.definedview.databinding.ActivityChartBinding;
import com.example.definedview.databinding.ActivityStateBinding;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;

public class ChartActivity extends AppCompatActivity {
    ActivityChartBinding activityChartBinding;
    List<PointValue> values = new ArrayList<>();
    List<Float> data = new ArrayList<>();

    //图表
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_chart);
        activityChartBinding = DataBindingUtil.setContentView(this, R.layout.activity_chart);
        String buf = readAssetsTxt(this, "test");
        //System.out.println(buf);
        //对String进行split之后的数组的输出
        String[] tt=buf.split("\\s+");
        //System.out.println(tt[0]);
        //System.out.println(tt[1]);
        for(int i=0; i<tt.length; i++){
            data.add(Float.valueOf(tt[i]));
        }

        initData();

        Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
        line.setCubic(true);
        List<Line> lines = new ArrayList<Line>();
        lines.add(line);

        LineChartData chartData = new LineChartData();
        chartData.setLines(lines);

        activityChartBinding.chart.setLineChartData(chartData);

    }

    private void initData() {
        for(int i=0; i<data.size(); i++){
            values.add(new PointValue(i, data.get(i)));
        }
    }

    /**
     * 读取assets下的txt文件，返回utf-8 String
     * @param context
     * @param fileName 不包括后缀
     * @return
     */
    public static String readAssetsTxt(Context context, String fileName){
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = context.getAssets().open(fileName+".txt");
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer, "utf-8");
            // Finally stick the string into the text view.
            return text;
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return "读取错误，请检查文件名";
    }

}
